//
//  SeleCtContrl.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/17.
//  Copyright © 2016年 game. All rights reserved.
//

#import "SeleCtContrl.h"
#import "SelectNavView.h"
#import "AFNetworking.h"
#import "SeleCtModel.h"
#import "SelectCell.h"
#import "SeletCommentCell.h"
#import "SelectthreadModel.h"
#import "ZanView.h"
#import "AticleFootView.h"
#import "TextPutView.h"
#import "QwardView.h"
#import "LoginController.h"
#import "OtherInformationCtrl.h"
#import "SelectShreaView.h"
#import "ReplyModel.h"
#import "MJRefresh.h"
#define ZanOrAwardWith ((SCREEN_WIDTH-7*11)/10+8)
@interface SeleCtContrl ()<UITableViewDataSource,UITableViewDelegate,TextPutViewDeleget,ZanViewClickDeleget,CommentCellDeleget,SelectCellDeleget,QwardViewDeleget>
@property (nonatomic,strong) SelectNavView *navView;
@property (nonatomic,strong) SeleCtModel *selecModel;
@property (nonatomic,assign) CGFloat SelecCellheight;
@property (nonatomic,assign) CGFloat CommetClleHight;
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) AticleFootView *footview;
@property (nonatomic,strong) ZanView *zanView;
@property (nonatomic,strong) TextPutView *textPutview;
@property (nonatomic,strong) QwardView *awarView;
@property (nonatomic,assign) NSInteger nextPage;
@property (nonatomic,strong) NSMutableArray *commentAry;
/**
 *  是否是对文章发表评论 YES为评论上的回复  NO为对文章进行评论
 */
@property (nonatomic,assign) BOOL isCommentAticl;
@property (nonatomic,copy) NSString *pid;
@property (nonatomic,assign) BOOL isShowFlood;
@property (nonatomic,strong) NSString *refrshUrl;

@property (nonatomic,assign) BOOL updating;
@property (nonatomic,strong) NSMutableDictionary *cellHightdic;

@property (nonatomic,strong) SelectShreaView *shareView;

/** 评论成功插入到第一条数据*/
@property (nonatomic, assign) BOOL isComment;
@property (nonatomic,strong) NSString *replayName;
@property (nonatomic,strong) NSString *replayMessage;
@end

@implementation SeleCtContrl


-(NSMutableDictionary *)cellHightdic{
    if (!_cellHightdic) {
        _cellHightdic = [NSMutableDictionary dictionary];
    }
    return _cellHightdic;
}

-(NSMutableArray *)commentAry{
    if (!_commentAry) {
        _commentAry = [NSMutableArray array];
    }
    return _commentAry;
}

#pragma mark--举报视图
-(SelectReportView *)reportView{
    if (!_reportView) {
        _reportView = [[NSBundle mainBundle]loadNibNamed:@"SelectReportView" owner:nil options:nil].lastObject;
        _reportView.frame = [UIScreen mainScreen].bounds;
        
        _reportView.alpha = 0;
        _reportView.fatherCtrl = self;
        [self.view addSubview:_reportView];
         [self.view sendSubviewToBack:_reportView];
    }
    return _reportView;
}

-(SelectNavView *)navView{
    if (!_navView) {
        _navView = [[SelectNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
        [_navView.bacBtn addTarget:self action:@selector(Selectback) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView.share addTarget:self action:@selector(ShareClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_navView];
        
    }
    return _navView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.navView.tid = self.tid;
}


-(void)Selectback{
    _awarView.selctCtrl = nil;
    _reportView.fatherCtrl = nil;
    _shareView.fatherCtrl = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(SelectShreaView *)shareView{
    
    if (!_shareView) {
        
        _shareView = [[SelectShreaView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT*0.4, SCREEN_WIDTH, SCREEN_HEIGHT*0.4)];
        
        _shareView.fatherCtrl = self;
    }
    return _shareView;
}

/**
 *  分享点击事件
 */
-(void)ShareClick:(UIButton *)btn{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        if (self.selecModel) {
            self.shareView.model = self.selecModel.thread;
            [self.shareView show];
        }else{
            [Manager GetHudWhithText:@"数据还未加载完成，不能进行分享" AndFatherView:self.view];
        }
        
    }else{
        LoginController *login = [LoginController new];
        [self.navigationController pushViewController:login animated:YES];
    }
}

-(void)GetData{
    self.refrshUrl = self.url;
    self.nextPage = 1;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSLog(@"%@",self.url);
    [manager GET:self.url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {

        self.selecModel = [[SeleCtModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
        self.reportView.model = self.selecModel.thread;
        
        [self.commentAry addObjectsFromArray:self.selecModel.postlist];

        if (self.isComment == YES) {
            
            [self.commentAry exchangeObjectAtIndex:0 withObjectAtIndex:self.commentAry.count-1];
            self.isComment = NO;
        }
        
        
        SelectthreadModel *model = self.selecModel.thread;
        self.awarView.tid = model.tid;
        self.awarView.pid = model.pid;
        self.awarView.formhash = self.selecModel.formhash;

        [MBProgressHUD hideHUDForView:self.view];
        [UIView transitionWithView:self.tableview duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            [_tableview reloadData];
        } completion:nil];
       
        [self CreatFootView];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.1), dispatch_get_main_queue(), ^{
            
            if (self.isSlide) {
                if (self.selecModel.postlist.count!=0) {
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
                    [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
                }
            }
        });
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [Manager GetHudWhithText:@"加载失败" AndFatherView:self.view];
   
    }];
}
#pragma 上拉加载网络请求
-(void)GetDataWhithPahe:(NSInteger)page{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *url=[self.url stringByAppendingFormat:@"&page=%ld",(long)page];

    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        SeleCtModel *model = [[SeleCtModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
        [self.commentAry addObjectsFromArray:model.postlist];
        [_tableview.footer endRefreshing];

        [_tableview reloadData];
        self.selecModel.total_page = model.total_page;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [_tableview.footer noticeNoMoreData];
    }];
}

-(void)CreatTableview{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0,64, SCREEN_WIDTH, SCREEN_HEIGHT-44-77) style:UITableViewStyleGrouped];
    _tableview.backgroundColor = [UIColor whiteColor];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableview registerClass:[SelectCell class] forCellReuseIdentifier:@"Selectcell"];
    
    [_tableview registerNib:[UINib nibWithNibName:@"SeletCommentCell" bundle:nil] forCellReuseIdentifier:@"commentCell"];
    [self.view addSubview:_tableview];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableview.width, 1)];
    view.backgroundColor = [UIColor whiteColor];
    _tableview.tableFooterView = view;
    _tableview.sectionFooterHeight = 0.f;
    _tableview.tableHeaderView = view;
    [self.view sendSubviewToBack:_tableview];
    

}
#pragma mark--上拉加载action
-(void)FootRefresh{
    self.nextPage +=1;

    if (self.nextPage>self.selecModel.total_page.integerValue) {
        
        [_tableview.footer noticeNoMoreData];
    }else{
        [self GetDataWhithPahe:self.nextPage];
    }
}

-(void)CreatFootView{

    [_footview removeFromSuperview];
    _footview = [[AticleFootView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-60, SCREEN_WIDTH, 60)];
    _footview.backgroundColor = [UIColor whiteColor];
    [_footview.textbtn addTarget:self action:@selector(footCommetView) forControlEvents:UIControlEventTouchUpInside];
    SelectthreadModel *threaModel = self.selecModel.thread;
    [_footview.comBtn setTitle:threaModel.replies forState:UIControlStateNormal];
    [_footview.comBtn addTarget:self action:@selector(CommentClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_footview];
    
    [_textPutview removeFromSuperview];
    _textPutview = [[TextPutView alloc]initWithFrame:self.view.bounds];
    _textPutview.alpha = 0;
    _textPutview.deleget = self;
    [self.view addSubview:_textPutview];
    
    _tableview.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(FootRefresh)];
    
    _tableview.footer.automaticallyHidden = YES;

}

//点击显示评论位置  tableview滑到评论位置
-(void)CommentClick{
    if (self.commentAry.count!=0) {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
        [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
    }
}

#pragma mark--底部点击评论，进入发表评论的TextView;
-(void)footCommetView{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        _textPutview.inputBar.placeHolder = @"说点什么呢?";
        _textPutview.alpha = 1;
        [_textPutview.inputBar.textView becomeFirstResponder];
    }else{
        LoginController *login = [LoginController new];
        [self.navigationController pushViewController:login animated:YES];
    }
}

/**
 *  点击发送  调用方法
 */
-(void)DidSender:(NSString *)sendText{

        if (self.isCommentAticl) {//回复评论
            
            [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
                if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                    [self replayWhithFormHash:responseObject[@"data"][@"formhash"] AndSendText:sendText];
                    
                }
            }];

           
        }else{
            
            
    [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            [self commentWhithFormHash:responseObject[@"data"][@"formhash"] AndSendText:sendText];
        
        }
    }];

  }
    
}

#pragma mark--评论文章
-(void)commentWhithFormHash:(NSString *)formhash AndSendText:(NSString *)sendText{
    SelectthreadModel *model = self.selecModel.thread;
    NSString *local = [NSString stringWithFormat:@"%@|%@|%@",[self.Myud valueForKey:@"longitude"],[self.Myud valueForKey:@"latitude"],[self.Myud valueForKey:@"localName"]];

    NSDictionary *dic = @{
                          @"fid":model.fid,
                          @"tid":model.tid,
                          @"message":sendText,
                          @"formhash":formhash,
                          @"replysubmit":@"yes",
                          @"location":local,
                          };
    [[Manager sharedManager]ResponseWhithURL:CommentUrl AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        if (error) {
            [Manager GetHudWhithText:@"发表失败，请检查网络" AndFatherView:self.view];
        }else{
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
        
            [Manager GetHudWhithText:@"发表评论成功" AndFatherView:self.view];
            PostlistModel *model = [PostlistModel new];
            model.pid = responseObject[@"data"][@"pid"];
             model.tid = responseObject[@"data"][@"tid"];
            model.avatar = self.app.userModel.avatar;
            model.author = self.app.userModel.username;
            model.authorid = self.app.userModel.uid;
            model.dateline = @"刚刚";
            model.message = sendText;
            model.imgs = NULL;
            model.attachments = NULL;
            model.level = self.app.userModel.user_level;
            model.replay = nil;
            model.total_support = @"0";
             model.location = [self.Myud valueForKey:@"localName"];
            [self.commentAry insertObject:model atIndex:0];
            [self.tableview reloadData];
            
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.1), dispatch_get_main_queue(), ^{
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
                    [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
                });

            _textPutview.inputBar.textView.text = @"";
            
        }else{
            [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self.view];
        
        }
        }
    }];
}

#pragma mark--评论回复
-(void)replayWhithFormHash:(NSString *)formhash AndSendText:(NSString *)sendText{

    SelectthreadModel *model = self.selecModel.thread;
    
    NSString *local = [NSString stringWithFormat:@"%@|%@|%@",[self.Myud valueForKey:@"longitude"],[self.Myud valueForKey:@"latitude"],[self.Myud valueForKey:@"localName"]];
    NSDictionary *dic = @{
                          @"fid":model.fid,
                          @"tid":model.tid,
                          @"message":sendText,
                          @"formhash":self.selecModel.formhash,
                          @"replysubmit":@"yes",
                          @"repquote":self.pid,
                          @"location":local,
                          };
    [[Manager sharedManager]ResponseWhithURL:CommentUrl AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            
            [Manager GetHudWhithText:@"回复成功" AndFatherView:self.view];
            
            PostlistModel *model = [PostlistModel new];
            model.pid = responseObject[@"data"][@"pid"];
            model.tid = responseObject[@"data"][@"tid"];
            model.avatar = self.app.userModel.avatar;
            model.author = self.app.userModel.username;
            model.authorid = self.app.userModel.uid;
            model.dateline = @"刚刚";
            model.message = sendText;
            model.imgs = NULL;
            model.attachments = NULL;
            model.level = self.app.userModel.user_level;
          
            model.total_support = @"0";
            ReplyModel *replay = [ReplyModel new];
            replay.name = self.replayName;
            replay.message = self.replayMessage;
            model.replay = replay;
            model.location = [self.Myud valueForKey:@"localName"];
            
            [self.commentAry insertObject:model atIndex:0];
            [self.tableview reloadData];
            
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.1), dispatch_get_main_queue(), ^{
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
                    [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:1 animated:YES];
                });
            _textPutview.inputBar.textView.text = @"";
            self.replayName = @"";
            self.replayMessage = @"";
        }else{
            self.replayName = @"";
            self.replayMessage = @"";
            [Manager GetHudWhithText:@"回复失败" AndFatherView:self.view];
        }
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if (section==0) {
        
        BOOL likecount = self.selecModel.thread.likes.count!=0;
        BOOL scorecount = self.selecModel.thread.evaluate_score.count!=0;
        return ZanOrAwardWith*2+ZanOrAwardWith*likecount+ZanOrAwardWith*scorecount;
        
    }else{
        return 0;}
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==0) {
        
        if (self.selecModel) {

            self.zanView.model = self.selecModel.thread;
            self.zanView.formHash = self.selecModel.formhash;
        }
            return self.zanView;
    }else{
            return nil;
    }
}

-(ZanView *)zanView{
    if (!_zanView) {
         _zanView = [[ZanView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
        _zanView.deleget = self;
    }
    return _zanView;
}

/**
 *  zanView上点赞 用过代理回到Mainpage页面
 */
-(void)ZanClickISLogin:(BOOL)islogin{
    if (islogin) {
       [self.deleget SelectAtcPraisWhithCellRow:self.rowOfCell];
    }else{
        LoginController *login = [LoginController new];
        [self.navigationController pushViewController:login animated:YES];
    }
}

-(void)Succerefresh{

    [self.tableview reloadData];
}
#pragma mark---点击打赏代理方法
-(void)awardClick:(BOOL)isLogin{
    
    if (isLogin) {
 
        if ([self.awarView.fileString isEqualToString:@"YES"]) {
            self.awarView.alpha = 1;
            self.awarView.deleget = self;
            self.awarView.isclick = YES;
            [self.view bringSubviewToFront:_awarView];
        }else{
        
            if (self.awarView.fileString==nil) {
                self.awarView.fileString = @"网络异常";
            }
        
            [Manager GetHudWhithText:self.awarView.fileString AndFatherView:self.view];
        }
        
    }else{
        LoginController *login = [LoginController new];
        [self.navigationController pushViewController:login animated:YES];
    }
}

-(void)AwardSuccess:(NSArray *)awardAry{

    self.zanView.awardAry = awardAry;
     [self.tableview reloadData];
}
#pragma mark---点击点赞人头像查看个人空间代理
-(void)ShowSpaceClick:(NSString *)uid{
    [self ToSpaceCtl:uid];
}

-(QwardView *)awarView{
    if (!_awarView) {
        _awarView = [[QwardView alloc]initWithFrame:self.view.bounds];
        _awarView.alpha = 0;
        _awarView.selctCtrl = self;
        [self.view addSubview:_awarView];
    }
    return _awarView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else{
        return self.commentAry.count;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 0.1+[[self.cellHightdic valueForKey:[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row]] floatValue];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        SelectCell *cell =[tableView dequeueReusableCellWithIdentifier:@"Selectcell"];
        cell.model = self.selecModel.thread;
        cell.deleget =self;
    
        [self.cellHightdic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row]];
        return cell;
       
        
    }else{

        SeletCommentCell *cell =[tableView dequeueReusableCellWithIdentifier:@"commentCell"];
        
        cell.deleget = self;
        if (self.commentAry.count>0) {
            
            cell.model = self.commentAry[indexPath.row];
        }
        [self.cellHightdic setValue:[NSString stringWithFormat:@"%f",cell.height] forKey:[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row]];

        return cell;
   }
}

#pragma mark---评论cell 在没有登录的情况下点赞代理方法
-(void)praimsNoLogin{
    LoginController *login = [LoginController new];
    [self.navigationController pushViewController:login animated:YES];
}

#pragma mark---评论cell 点击回复  或者点击评论内容的 回复操作代理
-(void)ReplayClickWhithUsername:(NSString *)username AndCommentId:(NSString *)commentPId AndMessage:(NSString *)message{
    
    if (![self.app.isLogin isEqualToString:@"YES"]) {
        LoginController *login = [LoginController new];
        [self.navigationController pushViewController:login animated:YES];
        
    }else{
        
        self.isCommentAticl  = YES;
        _textPutview.inputBar.placeHolder =[NSString stringWithFormat:@"@%@",username];
        _textPutview.alpha = 1;
        self.pid = commentPId;
        [_textPutview.inputBar.textView becomeFirstResponder];
        self.replayName = username;
        self.replayMessage = message;
    }
}
#pragma mark--在评论上点击用户头像与名字查看个人空间
-(void)UserHeadAndUserNameClick:(NSString *)uid{
    [self ToSpaceCtl:uid];
}
#pragma mark--在详情cell上点击用户头像与名字查看个人空间
-(void)ShowSpaceCLick:(NSString *)uid{
    [self ToSpaceCtl:uid];
}
-(void)ToSpaceCtl:(NSString *)uid{
    OtherInformationCtrl *space = [OtherInformationCtrl new];
    space.uid = uid;
    [self.navigationController pushViewController:space animated:YES];
}
#pragma mark--只看楼主
-(void)ShowFlood:(NSString *)tid AndAuthorId:(NSString *)authorId{
    
    [self.commentAry removeAllObjects];
    self.isShowFlood = !self.isShowFlood;
    self.nextPage = 1;
    
    if (!self.isShowFlood) {
         self.url = self.refrshUrl;
    }else{
        self.url =[NSString stringWithFormat:ViewFlood,(long)tid.integerValue,(long)authorId.integerValue];
    }
        [self GetDataWhithPahe:0];
}

-(void)NewAticleOfLinkWhithTid:(NSString *)tid AndTurl:(NSString *)tUrl{

    SeleCtContrl *str = [SeleCtContrl new];
    str.tid = tid;
    str.url = tUrl;
    [self.navigationController pushViewController:str animated:YES];

}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;

     [self creatHuD:nil];
    [self GetData];
    [self CreatTableview];
    self.nextPage =1 ;
    self.awarView.alpha = 0;
}

-(void)praimsFieleWhitMessage:(NSString *)message{

    [Manager GetHudWhithText:message AndFatherView:self.view];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}


@end